package org.example.java8.future;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author 夏焰波
 * @date 2020-07-15 22:55
 */
//34CompletableFuture之supplyAsync详细介绍
public class CompletableFutureInAction4 {
    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {
        //实现工厂接口，设置守护线程
        Executor executor = Executors.newFixedThreadPool(2, r -> {
            Thread t = new Thread(r);
            //设置非守护线程
            t.setDaemon(false);
            return t;
        });
        //这里的线程默认是守护线程，设置成非守护线程
        CompletableFuture.supplyAsync(CompletableFutureInAction4::get,executor)
                .whenComplete((v, t) -> {
                    Optional.of(v).ifPresent(System.out::println);
                    Optional.of(t).ifPresent(x -> x.printStackTrace());

                });
        System.out.println("i am not block");


    }

    private static double get() {
        try {
            Thread.sleep(RANDOM.nextInt(5000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return RANDOM.nextDouble();
    }
}
